<template>
  <div>
    <page-view>
      <template #option>
        <div class="btn-box">
          <el-button @click="exportForm" type="primary">
            <img :src="exportPng" style="width:16px;height:16px;margin-right:3px" />全部导出
          </el-button>
          <template v-if="!isFsscClient">
            <el-button v-if="!isSureChangeUser" type="default" @click="isSureChangeUser = true">调整审批人</el-button>
            <el-button v-if="isSureChangeUser" type="default" @click="isSureChangeUser = false">取消操作</el-button>
            <el-button v-if="isSureChangeUser" :disabled="selectData.length <= 0" type="primary" @click="adjustment">调整选中
            </el-button>
          </template>
        </div>
      </template>
      <template #form>
        <searFormFix :data-form="searchData" @on-search="handleSearch(ruleFormRef)" @on-reset="handleReset"
          ref="formRef" class="form-history" :model="searchData" :rules="rules">
          <el-form-item prop="bizTypeCode" label-width="90px">
            <el-select v-model="searchData.bizTypeCode" placeholder="请选择业务类型" clearable @change="bizTypeChange">
              <el-option v-for="item in bizTypeList" :key="item.docCode" :value="item.docCode" :label="item.docName" />
            </el-select>
          </el-form-item>
          <el-form-item prop="subBizTypeCodes">
            <subBizSelect v-model:value="searchData.subBizTypeCodes" :bizTypeName="searchData.bizTypeName"
              @subBizChange="subBizChange" emit-path/>
          </el-form-item>
          <el-form-item prop="formCode">
            <el-select v-model="searchData.formCode" placeholder="请选择表单" clearable :no-data-text="
              searchData.subBizTypeId ? '无数据' : '请先选择业务子类'
            ">
              <el-option v-for="item in formList" :key="item.formCode" :value="item.formCode" :label="item.formName" />
            </el-select>
          </el-form-item>
          <el-form-item prop="totalAmountStart">
            <NumberRange v-model:start="searchData.totalAmountStart" v-model:end="searchData.totalAmountEnd" end-prop="totalAmountEnd"
              startPlaceholder="开始金额" endPlaceholder="结束金额"/>
          </el-form-item>

          <div v-for="(item, index) in conditions" :key="index" class="item-condition">
            <el-form-item label prop>
              <el-select v-model="item.type" placeholder="请先选择业务类型" clearable @change="onItem(item.type,index)">
                <el-option v-for="el in conditionList" :key="el.fieldCode" :value="el.fieldCode" :label="el.fieldName"
                  :disabled="el.disabled" />
              </el-select>
            </el-form-item>

            <template v-for="(el, id) in conditionList" :key="id">
              <template v-if="item.type && item.type === el.fieldCode">
                <el-form-item v-if="el.downType == 2" label prop>
                  <LabelCascader :index="index" @handleChange="handleChange" :itemData="el" :value="item.value" :path="item.path"/>
                </el-form-item>
                <el-form-item v-else-if="el.downType == 1" label prop>
                  <LabelSelect :index="index" @handleChange="handleChange" :itemData="el" :value="item.value"/>
                </el-form-item>
                <el-form-item v-else-if="
                  el.fieldType.includes('String') || el.fieldType.includes('Boolean')
                ">
                  <LabelInput :index="index" @handleBlur="handleChange" :itemData="el" :value="item.value" />
                </el-form-item>
                <el-form-item v-else-if="
                  el.fieldType.includes('Date')
                ">
                  <LabelDateRange :index="index" @handleChange="handleChange" :itemData="el" :value="item.value"/>
                </el-form-item>
                <el-form-item v-else-if="
                  el.fieldType.includes('Int') ||
                  el.fieldType.includes('decimal')
                ">
                  <LabelInputNumber :index="index" @handleChange="handleChange" :itemData="el" :value="item.value"/>
                </el-form-item>
              </template>
            </template>
            <p class="item-reduce" @click="onReduceCondition(index, item.type, item)">x</p>
          </div>
          <el-button style="margin-right: 10px" class="add-plus" @click="onAddCondition">+ 添加新的筛选</el-button>
        </searFormFix>
      </template>
      <template #table="tableScope">
        <pubilc-table :table-data="tableData" :isSlot="false" :linkLoading="linkLoading"
          :tableHeight="tableScope.tableHeight" :list-config="newColumns" v-loading="loading" :page-data="pageData"
          :isDisabled="isDisabled" :showSelect="isSureChangeUser" :translateTextDeal="translateTextDeal"
          @on-selectChange="handleSelectionChange" @on-action="handleAction" @on-linkClick="onLinkClick">
          <template v-slot:relationInstanceCode>
            <el-table-column label="关联流程" prop="relationInstanceCode" width="180">
              <template v-slot="{row}">
                <el-link type="primary" v-for="item in row.relationInstanceCode" :key="item" @click="openFormDetail({flowId: item})">{{item}}</el-link>
              </template>
            </el-table-column>
          </template>
        </pubilc-table>
      </template>
    </page-view>
    <change-user :dialogVisible="dialogVisible" :selectData="selectData" @handleClose="handleClose"
      v-if="dialogVisible" />
    <DetailDialog :dialogVisible="detailVisible" v-if="detailVisible" :recordData="recordData"
      @handleClose="handleClose" />
  </div>
</template>
<script>
import api from "@/api/index";
import { onMounted, ref } from "vue";
import { formatListToTree ,openFormDetail} from "@/util/index";
import ChangeUser from "./components/changeUser.vue";
import DetailDialog from "./components/detailDialog.vue";
import LabelInput from "./components/label-input.vue";
import LabelSelect from "./components/label-select.vue";
import LabelCascader from "./components/label-cascader.vue";
import LabelInputNumber from "./components/label-input-number.vue";
import LabelDateRange from "./components/label-date-range.vue";
import { ElIcon, ElMessage, ElMessageBox } from "element-plus";
import { downloadFile } from '@/util/downFile'
import { statusText } from '@/util/index'
import exportPng from '@/assets/images/exportIcon.png'
import { useRoute } from 'vue-router'
import NumberRange from '@/components/numberRange/index.vue'

export default defineComponent({
  name: "FormHistory",
  components: {
    ChangeUser,
    LabelCascader,
    LabelSelect,
    LabelInput,
    DetailDialog,
    LabelInputNumber,
    LabelDateRange,
    ElIcon,
    NumberRange,
  },
  setup() {
    // iframe引入时传入的客户端标识
    const iframeClient = useRoute().query.client
    const isFsscClient = ref(iframeClient == 'fssclient')

    const dialogVisible = ref(false);
    const detailVisible = ref(false);
    const loading = ref(false);
    const subBizTypeList = ref([]);
    const recordData = ref([]);
    const conditions = ref([]);
    const publicConditions = ref([]);
    const conditionList = ref([]);
    const exportData = ref(null)
    const searchData = ref({
      bizTypeCode: null,
      conditions: null,
      createBy: null,
      createdOrganizationId: null,
      createdTime: null,
      flowInstanceCode: null,
      flowStatus: null,
      formCode: null,
      subBizTypeCode: null,
      updatedTime: null,
      bizTypeName: null,
      totalAmountStart: undefined,
      totalAmountEnd: undefined
    });
    const formRef = ref();
    const rules = reactive({
      bizTypeCode: [
        {
          required: true,
          message: "请选择业务类型",
          trigger: "blur",
        },
      ],
    });
    const tableData = ref([]);
    const pageData = ref({
      pageNum: 1,
      pageSize: 10,
      total: 0,
    });
    const selectData = ref([]);
    const formList = ref([]);
    const columns = [
      { alias: "bizTypeName", label: "业务类型", minWidth: "140" },
      { alias: 'subBizTypeName', label: '业务子类', minWidth: '180', type: 'link', },
      { alias: "formName", label: "表单名称", minWidth: "200" },
      { alias: "flowInstanceCode", label: "流程ID", minWidth: "200",type:'link' },
      { alias: "totalAmount", label: "金额", minWidth: "160" },
      { alias: "instanceCreatedName", label: "提交人", minWidth: "120" },
      {
        alias: "instanceCreatedOrganization",
        label: "提交人部门",
        minWidth: "200",
      },
      { alias: "instanceCreatedTime", label: "提交时间", minWidth: "200" },
      { alias: "instanceUpdatedTime", label: "更新时间", minWidth: "200" },
      { alias: "flowInstanceStatus", label: "流程状态", type: 'translateText', minWidth: "110" },
      { alias: "currentTaskName", label: "当前节点", minWidth: "140" },
      { alias: "currentTaskAssigneeName", label: "节点审批人", minWidth: "120" },
    ];
    if(!isFsscClient.value){
      columns.push({
        label: "操作",
        fixed: "right",
        listArr: [{ alias: "onRecord", label: "查看调整记录" }],
        width: "120px",
        type: "action",
      })
    }

    const newColumns = ref([...columns]);
    let isSureChangeUser = ref(false);
    let bizTypeList = ref([]);
    const subBizTypeRef = ref(null);
    const feildList = ref( ['createdOrganizationId', 'flowStatus', 'createBy', 'flowInstanceCode', 'createdTime', 'updatedTime'])
    const subBizTypeProps = {
      emitPath: false,
      value: "businessCode",
      label: "subBizName",
    };
    const onAddCondition = (row) => {
      conditions.value.push({
        type: "",
        value: "",
      });
    };
    const clearData = (type)=>{
      if (type) {
        let codeList = []
        conditionList.value.forEach((item) => {
          console.log(item.disabled,item.fieldCode)
        if (item.disabled==true) codeList.push(item.fieldCode)
      });
      let newList = JSON.parse(JSON.stringify(feildList.value))
      codeList.forEach(item=>{
        feildList.value.forEach((item2,index2)=>{
        if (item==item2) newList.splice(index2,1)
      })
      })
      newList.forEach(item=>{
        searchData.value[item] = null
      })
      } else {
        feildList.value.forEach(item=>{
        searchData.value[item] = null
      })
      }


    }
    const onReduceCondition = (index, type) => {
      conditions.value.splice(index,1);
      conditionList.value.forEach((item) => {
        if (item.fieldCode === type)  item.disabled = false;
      });
      if ( feildList.value.includes(type)) {
        searchData.value[type] = null;
      } else {
    publicConditions.value.splice( publicConditions.value.findIndex((item) => item.fieldCode === type),1);
      }
    };
    const onItem = (row,index) => {
      const arr = [];
      conditions.value.forEach((item) => {
        arr.push(item.type);
      });
      conditionList.value.forEach((item) => {
        if (arr.includes(item.fieldCode)) {
          item.disabled = true;
        } else {
          item.disabled = false;
        }
      });
      conditions.value[index].value = ''
      clearData(row)
    };

    const handleChange = (row, index, itemData,pathList) => {
      conditions.value.forEach(item=>{
        if (item.type==itemData.fieldCode) item.value = row.value
        if(Array.isArray(pathList)) item.path = pathList
      })
    //  clearData()
      if (feildList.value.includes(itemData.fieldCode)) {
        searchData.value[itemData.fieldCode] = row.value;
      } else {

       let findIndex =  publicConditions.value.findIndex(itemFind=>itemFind.fieldCode==itemData.fieldCode)
       if (findIndex>-1) {
        publicConditions.value[findIndex].fieldValue = row.value
       } else {
        publicConditions.value.push({
          fieldCode: itemData.fieldCode,
          fieldType: itemData.fieldType,
          fieldValue: row.value,
        });
       }

        publicConditions.value = uniqueArray(
          publicConditions.value,
          "fieldCode"
        );
      }

    };
    const uniqueArray = (array, key) => {
      let result = [array[0]];
      for (let i = 1; i < array.length; i++) {
        let item = array[i];
        let repeat = false;
        for (let j = 0; j < result.length; j++) {
          if (item[key] == result[j][key]) {
            repeat = true;
            break;
          }
        }
        if (!repeat) {
          result.push(item);
        }
      }
      return result;
    };

    const handleAction = ([config, data]) => {
      if (config.alias === "onRecord") {
        if (!data.adjustRecords || data.adjustRecords.length == 0) {
          ElMessage({
            message: `没有调整记录`,
            type: "warning",
          });
          return;
        }
        detailVisible.value = true;
        recordData.value = data.adjustRecords;
      } else {
        pageData.value[config] = data;
        getList();
      }
    };
    const handleSearch = async () => {
      pageData.value.pageNum = 1
      pageData.value.pageSize = 10
      getList()
    }

    // 借款单、事前申请类型
    const relationFlowTypes = ['jkhk','JKHK','jk','SQSQ','sqsq','BE_EV','BEEV','PREapply']

    // 列表查询
    const getList = async () => {

      if (!searchData.value.bizTypeCode || searchData.value.bizTypeCode == '') {
        return ElMessage({
          message: `请选择业务类型`,
          type: "warning",
        });
      }
      loading.value = true;
      if (publicConditions.value.length > 0) {
        searchData.value.conditions = JSON.stringify(
          publicConditions.value
        );
      } else {
        searchData.value.conditions = null
      }

      const method = isFsscClient.value ? 'formPageRecordReimburse' : 'formPageRecord'
      api.formHistory[method]({ ...searchData.value, subBizTypeCodes: searchData.value.subBizTypeCodes.flat() , ...pageData.value })
        .then((res) => {
          newColumns.value = [...columns]
          exportData.value = { ...searchData.value, ...pageData.value }
          loading.value = false;
          const arr = [];
          const tableList = []
          res.formCommonField.forEach((item) => {
            arr.push({
              alias: item.fieldCode,
              label: item.fieldName,
              minWidth: "150",
            });
          });

          res.pageResult.list.forEach(item => {
            tableList.push({ ...item, ...JSON.parse(item.commonField) })
          })
          newColumns.value.splice(4, 0, ...arr);

          if (relationFlowTypes.indexOf(searchData.value.bizTypeCode) > -1) {
            newColumns.value.push({
              alias: "relationInstanceCode", label: "关联流程", minWidth: "200", type: 'slot'
            })
          }

          tableData.value = tableList;
          pageData.value.total = res.pageResult.total;
        })
        .catch(() => {
          loading.value = false;
        });


    };
    const isDisabled = (row, index) => {
      if (Number(row.flowInstanceStatus) === 2) {
        return 1;
      }
      return 0
    };
    const handleSelectionChange = (row) => {
      selectData.value = row;
    };
    const translateTextDeal = (item, val) => {
      const map = [
        { label: '手动结束', value: '0' },
        { label: '流转完成', value: '1' },
        { label: '进行中', value: '2' }
      ]
      return statusText(map, val)
    }
    const exportForm = () => {
      if (!exportData.value) {
        ElMessage({
          type: 'warning',
          message: '请先查询后导出!'
        });
        return
      }
      const method = isFsscClient.value ? 'exportFormRecordReimburse' : 'exportFormRecord'
      loading.value = true
      api.formHistory[method](exportData.value)
        .then((res) => {
          loading.value = false
          if (res) {
            downloadFile(res, '表单记录', 'xlsx')
          } else {
            ElMessage({
              type: 'error',
              message: '没有数据!'
            });
          }
        })
        .catch(() => {
          loading.value = false
        })
    };
    const adjustment = () => {
      if (selectData.value.length <= 0) {
        ElMessage({
          message: `请选择需要调整的数据`,
          type: "warning",
        });
        return;
      }
      dialogVisible.value = true;
    };
    const handleClose = (type) => {
      dialogVisible.value = false;
      detailVisible.value = false;
      if (type === 1) {
        handleSearch();
      }
    };
    const handleReset = () => {
      searchData.value.subBizTypeName = "";
      subBizTypeList.value = [];
      formList.value = [];
      conditions.value = [];
      searchData.value.bizTypeName = ''
    };
    const subTypeChange = (subTypeId) => {
      let checkItem = subBizTypeRef.value.getCheckedNodes(true);
      if (checkItem && checkItem.length > 0) {
        searchData.value.subBizTypeName = checkItem[0].data.subBizName;
      }
      if (searchData.value.subBizTypeId) {
        getFormList(searchData.value.subBizTypeId);
      }
    };
    const subBizChange = (val) => {
      searchData.value.formCode = ''
      if (!val || val.length <= 0) {
        return false
      }

      api.formHistory.getFormListBySubBiz(val.flat()).then(res => {
        formList.value = res || []
      })
    }
    const requestSubBusinessTypeList = (bizTypeName) => {
      subBizTypeList.value = [];
      if (!bizTypeName) {
        return;
      }
      api.reimbursement.getSubTypeListByBizName(bizTypeName).then((data) => {
        subBizTypeList.value = formatListToTree(data);
      });
    };
    // 请求业务类型列表
    const requestBusinessTypeList = () => {
      api.reimbursement.getTypeList().then((data) => {
        bizTypeList.value = data || [];
      });
    };
    const bizTypeChange = async (bizTypeCode) => {
      clearData()
      searchData.value.conditions = null
      searchData.value.subBizTypeId = "";
      searchData.value.subBizTypeName = "";
      searchData.value.subBizTypeCodes = []
      publicConditions.value = []
      conditions.value = [];
      let obj = {};
      obj = bizTypeList.value.find((item) => {
        return item.docCode === bizTypeCode;
      });
      await requestSubBusinessTypeList(obj.docName);
      searchData.value.bizTypeName = obj.docName
      await api.formHistory.getConditions({ bizTypeCode }).then((res) => {
        console.log(JSON.parse(res));
        conditionList.value = JSON.parse(res);
      });
      handleSearch()
    };
    const getFormList = (subBizCode) => {
      api.reimbursement.getFormListBySubType({ subBizCode }).then((res) => {
        formList.value = res || [];
      });
    };
    const linkLoading = ref(false)
    const onLinkClick = ([name, row]) => {
      if (name === 'subBizTypeName') {
        linkLoading.value = true
        api.reimbursement.getSubBizTypePath(row.subBizTypeCode).then((res) => {
          ElMessageBox.alert(res, '业务子类完整路径', {
            closeOnClickModal: true
          })
          linkLoading.value = false
        }).catch(() => {
          linkLoading.value = false
        })
      }
      if (name=='flowInstanceCode') {
        openFormDetail({flowId:row.flowInstanceCode})
      }
    }
    onMounted(() => {
      requestBusinessTypeList();
    });
    return {
      rules,
      formRef,
      getFormList,
      bizTypeChange,
      subTypeChange,
      newColumns,
      isSureChangeUser,
      tableData,
      pageData,
      handleAction,
      handleSelectionChange,
      handleSearch,
      handleReset,
      subBizTypeProps,
      searchData,
      bizTypeList,
      loading,
      formList,
      onItem,
      dialogVisible,
      detailVisible,
      subBizTypeList,
      subBizTypeRef,
      onAddCondition,
      onReduceCondition,
      conditions,
      handleChange,
      conditionList,
      selectData,
      handleClose,
      recordData,
      adjustment,
      exportForm,
      translateTextDeal,
      isDisabled,
      exportPng,
      onLinkClick,
      linkLoading,
      subBizChange,
      isFsscClient,
      openFormDetail
    };
  },
});
</script>
<style lang="scss" scoped>
.form-history {
  background: #fff;

  .item-condition {
    display: inline-block;
    position: relative;

    .item-reduce {
      width: 16px;
      height: 16px;
      line-height: 13px;
      font-size: 12px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #ff5e04;
      position: absolute;
      right: 10px;
      top: -20px;
      cursor: pointer;
      z-index: 20;
    }
  }

  .add-plus {
    margin-bottom: 18px;
  }
}
</style>
